import gtk
import os
import utils

class Setup(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)
        self.set_size_request(800, 500)
        self.set_title("Hydroxygen Configurator")
        
        icon=utils.getPixbufFromName("./images/logo.png", 48)
        self.set_icon_list(icon)
        
        VBox=gtk.VBox(spacing=5)
        
        okButton=gtk.Button(gtk.STOCK_OK)
        okButton.set_use_stock(True)
        cancelButton=gtk.Button(gtk.STOCK_CANCEL)
        cancelButton.set_use_stock(True)
        self.homeButton=gtk.Button("Change Home Icon")
        hicon=gtk.Image()
        hicon.set_from_pixbuf(utils.getPixbufFromName("user-home", 22))
        self.homeButton.set_image(hicon)
        self.homeButton.set_use_stock(True)
        okButton.connect("clicked", self.ok)
        cancelButton.connect("clicked", self.cancel)
        self.homeButton.connect("clicked", self.home)
        HButtonBox=gtk.HBox()
        HButtonBox.pack_start(self.homeButton, False, False, 5)
        HButtonBox.pack_end(okButton, False, False, 5)
        HButtonBox.pack_end(cancelButton, False, False, 5)
        
        HBox=gtk.HBox(spacing=5)
        self.list=utils.read_options()
        
        self.app_list=AppList(self.list)
        Scroll=gtk.ScrolledWindow()
        Scroll.add_with_viewport(self.app_list)
        Scroll.set_size_request(200, -1)
        Scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        HBox.pack_start(Scroll, False)
        self.icons=Icons(self.list, self.refresh_list, [])
        Scroll2=gtk.ScrolledWindow()
        Scroll2.add_with_viewport(self.icons)
        Scroll2.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        HBox.pack_end(Scroll2)
        
        self.app_list.connect("cursor-changed", self.el_changed)
        
        VBox.pack_start(HBox)
        VBox.pack_end(HButtonBox, False, False, 5)
        self.add(VBox)
        self.connect("delete-event", self.cancel)
        
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.show_all()
        gtk.main()

    def home(self, obj):
        dialog=gtk.FileChooserDialog(title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_current_folder(os.path.expanduser("~"))
        filter = gtk.FileFilter()
        filter.set_name(".png / .svg")
        filter.add_mime_type("image/png")
        filter.add_mime_type("image/svg+xml")
        filter.add_pattern("*.png")
        filter.add_pattern("*.svg")
        dialog.add_filter(filter)
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            filename=dialog.get_filename()
            print filename, 'selected'
            os.system("cp "+filename+" "+filename+".temp.png")
            os.system("mogrify -resize 16x16 "+filename+".temp.png")
            os.system("mv "+filename+".temp.png "+os.path.expanduser("~")+"/.icons/hydroxygen/16x16/places/user-home.png")
            os.system("cp "+filename+" "+filename+".temp.png")
            os.system("mogrify -resize 22x22 "+filename+".temp.png")
            os.system("mv "+filename+".temp.png "+os.path.expanduser("~")+"/.icons/hydroxygen/22x22/places/user-home.png")
            os.system("cp "+filename+" "+filename+".temp.png")
            os.system("mogrify -resize 24x24 "+filename+".temp.png")
            os.system("mv "+filename+".temp.png "+os.path.expanduser("~")+"/.icons/hydroxygen/24x24/places/user-home.png")
            os.system("cp "+filename+" "+filename+".temp.png")
            os.system("mogrify -resize 32x32 "+filename+".temp.png")
            os.system("mv "+filename+".temp.png "+os.path.expanduser("~")+"/.icons/hydroxygen/32x32/places/user-home.png")
            os.system("cp "+filename+" "+filename+".temp.png")
            os.system("mogrify -resize 48x48 "+filename+".temp.png")
            os.system("mv "+filename+".temp.png "+os.path.expanduser("~")+"/.icons/hydroxygen/48x48/places/user-home.png")
            os.system("cp "+filename+" "+filename+".temp.png")
            os.system("mogrify -resize 72x72 ."+filename+".temp.png")
            os.system("mv "+filename+".temp.png "+os.path.expanduser("~")+"/.icons/hydroxygen/72x72/places/user-home.png")
            os.system("cp "+filename+" "+filename+".temp.png")
            os.system("mogrify -resize 128x128 "+filename+".temp.png")
            os.system("mv "+filename+".temp.png "+os.path.expanduser("~")+"/.icons/hydroxygen/128x128/places/user-home.png")
            
            utils.Refresh()
            hicon=gtk.Image()
            hicon.set_from_pixbuf(utils.getPixbufFromName("user-home", 22))
            self.homeButton.set_image(hicon)

        elif response == gtk.RESPONSE_CANCEL:
            print 'Closed, no files selected'
        dialog.destroy()
    
    def ok(self, obj):
        #Qui va aggiornato il tema.
        self.list=self.icons.get_list()
        last=utils.read_last_options()
        i=0;
        file=open(os.path.expanduser("~")+"/.hydroxygenrc", "w")
        for el in self.list:
            if last==None or len(last)<=i:
                file.write(el["choice"].split("/")[0]+"\n")
            elif el["choice"]==el["icon"]:
                file.write(last[i]+"\n")
            else: file.write(el["choice"].split("/")[0]+"\n")
            if el["choice"]!=el["icon"]:
                pid=os.fork()
                if pid==0:
                    os.chdir(os.path.expanduser("~")+"/.icons/hydroxygen/")
                    os.execvp("bash", ["bash", "change-type.sh", el["choice"].split("/")[0]])
                os.waitpid(pid, 0)
            i+=1
        file.close()
        
        utils.Refresh()
        self.hide()
        gtk.main_quit()

    def cancel(self, obj, event=None):
        self.hide()
        gtk.main_quit()
    
    def el_changed(self, obj):
        index=self.app_list.get_selected()
        self.icons.set_list(index)
    
    def refresh_list(self, list):
        self.list=list
        self.app_list.refresh(self.list)        
    
class AppList(gtk.TreeView):
    def __init__(self, list):
        gtk.TreeView.__init__(self)
        self.list=list
        self.model = gtk.ListStore (gtk.gdk.Pixbuf, str, int)
        COL_ICON, COL_NAME, COL_INDEX = (0, 1, 2)
        
        self.set_model(self.model)
        self.treeselection = self.get_selection()
        self.treeselection.set_mode (gtk.SELECTION_SINGLE)

        cell = gtk.CellRendererPixbuf ()
        column = gtk.TreeViewColumn ('#', cell, pixbuf = COL_ICON)
        self.append_column (column)
    
        cell = gtk.CellRendererText ()
        column = gtk.TreeViewColumn ('Model', cell, text = COL_NAME)
        self.append_column (column)
        
        self.load()
    
    def load(self):
        index=0
        for el in self.list:
            icon=el["choice"].split("/")
            if len(icon)>=2:
                icon=icon[1]
            else: icon=icon[0]
            self.model.append([utils.getPixbufFromName(icon, 48, "app"), el["name"], index])
            index+=1
    
    def get_selected(self):
        model, iter = self.treeselection.get_selected()
        if iter:
            id=model.get_value (iter, 2)
            return id
        return -1
        
    def clean_list(self):
        self.model.clear()
    
    def refresh(self, list):
        self.list=list
        self.clean_list()
        self.load()
    
class Icons(gtk.VBox):
    def __init__(self, complete_list, refresh,name=None, list=[]):
        gtk.VBox.__init__(self)
        self.refresh=refresh
        self.complete_list=complete_list
        self.list_name=name
        self.list=list
        self.redraw()
    
    def redraw(self):
        for child in self.get_children():
            self.remove(child)
            del child
        
        HBox=gtk.HBox()
        self.pack_start(HBox, False)
        index=0
        while index<len(self.list):
            if (index)%4==0:
                HBox=gtk.HBox()
                self.pack_start(HBox, False)
            newButton=gtk.ToggleButton()
            image=gtk.Image()
            image_name=self.list[index].split("/")
            if len(image_name)>=2:
                image_name=image_name[1]
            else: image_name=image_name[0]
            image.set_from_pixbuf(utils.getPixbufFromName(image_name, 100))
            newButton.set_image(image)
            newButton.set_size_request(150, 150)
            if (self.list[index]!=self.complete_list[self.list_name]["choice"]):
                newButton.set_active(False)
            else: newButton.set_active(True)
            newButton.set_tooltip_text(self.list[index])
            newButton.connect("toggled", self.click, index)
            HBox.pack_start(newButton, False)
            index+=1
            
        self.show_all()
    
    def click(self, obj, index):
        
        self.complete_list[self.list_name]["choice"]=self.list[index]
        self.redraw()
        self.refresh(self.complete_list)
    
    def set_list(self, name):
        self.list=self.complete_list[name]["option-list"]
        self.list_name=name
        self.redraw()
    
    def get_list(self):
        return self.complete_list
    
